package net.luoran.dvm.controller;

import cn.hutool.core.util.IdUtil;
import net.luoran.dvm.common.base.Result;
import net.luoran.dvm.common.util.FileUtil;
import net.luoran.dvm.entity.SysFileDO;
import net.luoran.dvm.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * <p>
 * 文件 前端控制器
 * </p>
 *
 * @author MyBatisPlusGenerater
 * @since 2020-10-29
 */
@Controller
@RequestMapping("/sysFile")
public class SysFileController {

    @Value("${upload.file.path}")
    public String basePath;

    @Autowired
    private SysFileService sysFileService;

    /**
     * 上传封面图
     *
     * @param files
     * @return
     */
    @PostMapping("/uploadImage")
    @ResponseBody
    public Result uploadImage(@RequestParam("file") MultipartFile[] files, String operation, String fileId) {
        Result result = Result.ok();
        try {
            if (files.length == 0) {
                result = Result.error("文件不能为空");
                return result;
            }

            Map<String, String> resultMap = FileUtil.upload(files[0], basePath);
            SysFileDO sysFileDO = new SysFileDO();

            if ("insert".equals(operation)) {
                sysFileDO.setFileId(IdUtil.simpleUUID());
                sysFileDO.setFileName(resultMap.get("oldName"));
                sysFileDO.setFilePath(resultMap.get("path"));
                sysFileDO.setFileUrl("upload/" + resultMap.get("newName"));
                sysFileService.save(sysFileDO);
            } else {
                //修改还要删除旧的封面图
                //删除旧照片信息
                SysFileDO oldFile = sysFileService.getById(fileId);
                FileUtil.deleteFile(oldFile);

                sysFileDO.setFileId(fileId);
                sysFileDO.setFileName(resultMap.get("oldName"));
                sysFileDO.setFilePath(resultMap.get("path"));
                sysFileDO.setFileUrl("upload/" + resultMap.get("newName"));
                sysFileService.updateById(sysFileDO);
            }
            result.setData(sysFileDO);
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.error("系统错误,请重新上传");
        }
        return result;
    }

}
